package com.zjzywl.smoke.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zjzywl.smoke.util.WebResult;

/*
 * 厂家：罗万
 * 产品：液位计
 */

@RestController
@RequestMapping(value = "/liquid")
public class LiquidController {
	@RequestMapping(value = "/front/GetInfo")
	public WebResult doGet(Model model, HttpServletResponse response, HttpServletRequest request) throws Exception {

		String resp = null;

		JSONObject obj = new JSONObject();
		obj.put("CliToken", "91e3e901-2078-4a33-be71-0723538707d3");
		obj.put("CliTime", 1528075668);
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("AppEUI", "c4cd820b127e2e31");
		map.put("DevEUI", "c4cd82f41b3fc001");
		map.put("Namespace", "liquid");
		obj.put("Payload", map);
		obj.put("Signature", "O7YhLuE3S0NBCnc9DD73gg==");

		String json = obj.toString();
		System.out.println(json);
		try {
			URL url = new URL("http://linkwan.lowaniot.com:10236/liquid/front/GetInfo"); // url地址

			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Content-Type", "application/json");
			connection.connect();

			try (OutputStream os = connection.getOutputStream()) {
				os.write(json.getBytes("UTF-8"));
			}

			try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
				String lines;
				StringBuffer sbf = new StringBuffer();
				while ((lines = reader.readLine()) != null) {
					lines = new String(lines.getBytes(), "utf-8");
					sbf.append(lines);
				}
				resp = sbf.toString();

			}
			connection.disconnect();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			System.out.println("resp::::" + resp);
			JSONObject jsona = (JSONObject) JSON.parse(resp);
			Object object = jsona.get("Payload");
			System.out.println(object);
			return WebResult.OK(jsona);
		}

	}
}
